<?php
header("Content-type: text/html; charset=utf-8");
ini_set("display_errors", "On");
error_reporting(E_ALL | E_STRICT);

ini_set('date.timezone','Asia/Shanghai');

//定义常量
define('ROOT_PATH', dirname (__FILE__));

//服务器通信Api
define('HOST_URL','https://api.xiaomashengxian.com');
//define('HOST_URL','http:localhost:81');

//支付服务器通信令牌
define('WX_PAY_TOKEN', 'XGGHFIYTFI5468GHGH589HHGYGOY86');

//支付宝ID
define('APP_ID', '2017102709553396');

//商户ID
define('SELLER_ID', '2088821288106204');

//是否开启测试模式
define('AliPay_Debug', false);


//简易日志。
function logs($text) {
    $filepath = ROOT_PATH.'/logs/log-'.date('Y-m-d').'.txt';
    file_put_contents($filepath, date ( "Y-m-d H:i:s" ) . "  " . $text . "\r\n", FILE_APPEND );
}



/*
 * 模拟post请求
 */
 function curlPost($url, $data) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // post数据
    curl_setopt($ch, CURLOPT_POST, 1);
    // post的变量
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

    $output = curl_exec($ch);
    curl_close($ch);

    if( preg_match('/^\xEF\xBB\xBF/', $output) ) {
        $output = substr($output,3);
    }
    $res = json_decode(trim($output), true);  logs($url.': '.var_export($data,true)); logs('返回:'.var_export($res,true));
    if($res){
    	return $res;
    }

    return $output;
}

/*
 * 判断是否是微信浏览器
 */
function isWx() {
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
        return true;
    }

    return false;
}


/*
 * 登录状态写入
 */
function login($login){
	if(!$login){
		return false;
	} 

 	setcookie('uid', $login['uid'],0,'/');
    setcookie('time', $login['time'],0,'/');
    setcookie('token', $login['token'],0,'/');

    return true;
}

/**  Desc 获取当前IP */
function getIp() {
    if (getenv('HTTP_CLIENT_IP')) {
        $ip = getenv('HTTP_CLIENT_IP');
    }
    elseif (getenv('HTTP_X_FORWARDED_FOR')) {
        $ip = getenv('HTTP_X_FORWARDED_FOR');
    }
    elseif (getenv('HTTP_X_FORWARDED')) {
        $ip = getenv('HTTP_X_FORWARDED');
    }
    elseif (getenv('HTTP_FORWARDED_FOR')) {
        $ip = getenv('HTTP_FORWARDED_FOR');

    }
    elseif (getenv('HTTP_FORWARDED')) {
        $ip = getenv('HTTP_FORWARDED');
    }
    else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}


//通信签名生成
function serve_sign($temp){
    $token =  WX_PAY_TOKEN; 
    $code  =  md5(md5($temp.$token).$token);
    return $code;
}


//通信签名验证
function check_serve_sign($code,$token_code)
{
    $token = serve_sign($token_code);

    if($token != $code){
        return  false;
    }

    return true;
}


//对象转数组
function object_array($array){  
    if(is_object($array)) {  
        $array = (array)$array;  
     } if(is_array($array)) {  
         foreach($array as $key=>$value) {  
             $array[$key] = object_array($value);  
        }  
     }  
     return $array;  
}